﻿using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using WebDAVSharp.Server.Exceptions;
using WebDAVSharp.Server.Stores;
using WebDAVSharp.Server.Stores.DiskStore;

namespace AzureStorageLight
{
    public class BackupWebDavStoreDocument : BackupWebDavStoreItem, IWebDavStoreDocument
    {
        public BackupWebDavStoreDocument(BackupWebDavStoreCollection parentCollection, CloudBlockBlob item)
            : base(parentCollection, item, MakeSnapshotName(item))
        {
        }

        public string Etag
        {
            get
            {
                return StorageItemUtil.Md5HashStringForUtf8String(Snapshot.Name + Snapshot.SnapshotTime.ToString());
            }
        }

        public string MimeType
        {
            get
            {
                return "*/application";
            }
        }

        public long Size
        {
            get
            {
                return -1;
            }
        }

        public override DateTime ModificationDate
        {
            get
            {
                if (Snapshot.IsSnapshot)
                {
                    return Snapshot.SnapshotTime.Value.DateTime;
                }
                else
                {
                    return Snapshot.Properties.LastModified.Value.DateTime;
                }
            }
        }


        public Stream OpenReadStream()
        {
            var st = new MemoryStream();
            var temp = Path.GetTempFileName();
            try
            {
                Snapshot.DownloadToFileAsync(temp, FileMode.Create).Wait();
                using (var fs = new FileStream(temp, FileMode.Open))
                {
                    fs.CopyTo(st);
                }
            }
            finally
            {
                File.Delete(temp);
            }
            st.Seek(0, SeekOrigin.Begin);
            return st;

        }

        public Stream OpenWriteStream(bool append)
        {
            throw new WebDavUnauthorizedException();
        }

    }
}